#define _CRT_SECURE_NO_WARNINGS 1

#include<stdio.h>

struct ListNode* removeElements(struct ListNode* head, int val) {
    if (!head)
        return NULL;
    struct ListNode* p = head, * q = p->next;
    while (q) {
        if (p->val == val) {
            head = q;
            free(p);
            p = q;
            q = q->next;
        }
        else if (q->val != val) {
            p = p->next;
            q = q->next;
        }
        else {
            p->next = q->next;
            free(q);
            q = p->next;
        }
    }
    if (p->val == val) {
        return NULL;
    }
    return head;
}
